package mall.service;


import mall.core.jdbc.Page;
import mall.entity.Product;
import mall.repository.CategoryDao;
import mall.repository.ProductDao;

import java.util.List;
import java.util.stream.Collectors;

public class ProductService {
    private final ProductDao productDao = new ProductDao();
    private final CategoryDao categoryDao = new CategoryDao();

    public List<Product> list() {
        return productDao.selectList(new Product()).stream().map(this::details).collect(Collectors.toList());
    }

    public List<Product> list(String name) {
        Product product = new Product();
        product.setName(name);
        return productDao.selectList(product).stream().map(this::details).collect(Collectors.toList());
    }

    public List<Product> list(Product product) {
        return productDao.selectList(product).stream().map(this::details).collect(Collectors.toList());
    }

    public Product getById(int id) {
        return productDao.selectById(id);
    }

    public int update(Product product) {
        return productDao.updateById(product);
    }

    public int add(Product product) {
        return productDao.insert(product);
    }

    public int deleteById(int id) {
        return productDao.deleteById(id);
    }


    public Product details(Product product) {
        if (product.getCategoryId() != null) {
            product.setCategory(categoryDao.selectById(product.getCategoryId()));
        }
        return product;
    }

    public Page<Product> page(Page<Product> page, Product product) {
        Integer total = productDao.count(product);
        List<Product> list = productDao.selectList(product, page.getOffset(), page.getPageSize());
        List<Product> collect = list.stream().map(this::details).collect(Collectors.toList());
        page.setList(collect);
        page.setTotal(total);
        return page;
    }
}
